import vtk
import numpy as np


def generate_colored_point_cloud():
    """
    创建带有颜色的散点云。
    """
    points = vtk.vtkPoints()
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)  # RGB 颜色
    colors.SetName("Colors")

    # 生成一些随机点和颜色
    num_points = 100
    for i in range(num_points):
        x, y, z = np.random.uniform(-5, 5, 3)  # 随机点
        r, g, b = np.random.randint(0, 256, 3)  # 随机颜色
        points.InsertNextPoint(x, y, z)
        colors.InsertNextTuple3(r, g, b)

    # 创建 vtkPolyData
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.GetPointData().SetScalars(colors)
    return polydata


def generate_surface_from_points(point_cloud):
    """
    从点云生成颜色渐变的曲面。
    """
    # Delaunay2D 用于生成曲面
    delaunay = vtk.vtkDelaunay2D()
    delaunay.SetInputData(point_cloud)
    delaunay.Update()

    # 插值颜色
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(delaunay.GetOutputPort())
    mapper.SetScalarModeToUsePointData()
    mapper.Update()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    return actor


def main():
    # 创建点云
    point_cloud = generate_colored_point_cloud()

    # 从点云生成曲面
    surface_actor = generate_surface_from_points(point_cloud)

    # VTK 渲染设置
    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    # 添加点云和曲面到渲染器
    point_actor = vtk.vtkActor()
    point_mapper = vtk.vtkPolyDataMapper()
    point_mapper.SetInputData(point_cloud)
    point_mapper.SetScalarModeToUsePointData()
    point_actor.SetMapper(point_mapper)

    renderer.AddActor(point_actor)  # 添加点云
    renderer.AddActor(surface_actor)  # 添加曲面

    # 渲染窗口设置
    renderer.SetBackground(0.1, 0.1, 0.1)  # 背景颜色
    render_window.SetSize(800, 600)
    render_window.Render()
    render_window_interactor.Start()


if __name__ == "__main__":
    main()
